package sk.ygor.raynor.client.json.collectiontype;

import sk.ygor.raynor.client.json.JSONSerializer;
import sk.ygor.raynor.client.json.JSONSerializationException;

import java.util.List;
import java.util.ArrayList;

import com.google.gwt.json.client.JSONValue;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNull;

@SuppressWarnings({"UnusedDeclaration"}) // used internally in generated serializers
public class java_util_List_JSONSerializer<T> extends CollectionTypeSerializer<List<T>> {

    private JSONSerializer<T> itemSerializer;

    public java_util_List_JSONSerializer(JSONSerializer<T> itemSerializer) {
        this.itemSerializer = itemSerializer;
    }

    public List<T> deserialize(JSONValue jsonValue) {
        if (jsonValue == null || jsonValue.isNull() != null) {
            return null;
        }
        JSONArray jsonArray = jsonValue.isArray();
        if (jsonArray == null) {
            throw new JSONSerializationException("Not a JSONArray. Cannot create List from: " + jsonValue.toString());
        }
        ArrayList<T> list = new ArrayList<T>();
        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(itemSerializer.deserialize(jsonArray.get(i)));
        }

        return list;
    }

    public JSONValue serialize(List<T> javaObject) {
        if (javaObject == null) {
            return JSONNull.getInstance();
        }
        JSONArray jsonArray = new JSONArray();
        int i = 0;
        for (T obj : javaObject) {
            jsonArray.set(i, itemSerializer.serialize(obj));
            i++;
        }
        return jsonArray;
    }

}
